<template>
  <div id="app"> 
    <div class="common-layout">
      <el-container>  
        <el-aside width="200px" style="background-color:gray">
        
          <!-- <div>
              <button @click="addChat()" class="addChat">
                新会话
              </button>
          </div> -->
          <template v-for="(item, index) in chatinfos" :key="index">
                <div @click="selChatInfo(item.userChatGuid)" >                        
                  <div :class="{'chatTitleCurDiv':userChatGuid == item.userChatGuid,'chatTitleDiv':userChatGuid != item.userChatGuid}">
                    {{item.external_userid}}
                  </div>                  
                </div>
            </template>
        </el-aside>
        <el-main>
          <div class="chatbox-container">
          <div class="container">
            <h1>Ai Chat Bot</h1>
          <div class="messageBox mt-8" id="mesarea">
            <template v-for="(message, index) in messages" :key="index">
              <div :class="message.from == 'user' ? 'messageFromUser' : 'messageFromChatGpt'">
                <div :class="message.from == 'user' ? 'userMessageWrapper' : 'chatGptMessageWrapper'">
                  <div :class="message.from == 'user' ? 'userMessageContent' : 'chatGptMessageContent'">{{ message.data }}</div>
                </div>
              </div>
            </template>
          </div>
        
          <div class="inputContainer">
            <div style="background-color: #f7f7f7;margin-right: 10px;">
              <button @click="clearMessage()" class="clearButton">
                Clear
              </button>
            </div>  
            <input
              v-model="currentMessage"
              type="text"
              class="messageInput"
              placeholder="Ask me anything..."
            />
            <el-button
              @click="sendMessage(currentMessage)"
              
              :disabled="askBtnDisabled"
              type="primary" 
            >
              Ask
            </el-button>
          </div>
          </div>
          </div>
        </el-main>        
      </el-container>
    </div>        
  </div>
</template>

<script >
import axios from 'axios';
// import signalr from '../../utils/signalR'
import * as signalR from '@microsoft/signalr';

export default {
  name: 'ChatBox',
  data() {
    return {
      currentMessage: '',
      messages: [],
      chatinfos:[],
      userGuid:"",
      userChatGuid:"",
      askBtnDisabled:false,
    };
  },
   created(){
    // this.initChatInfo();
  },
  mounted () {

    // const url = "http://localhost/mySignalRHub";
    const url = "http://testweb.zhusiot.com/mySignalRHub";
    // const url = "http://120.27.122.216/mySignalRHub";
    
    const signal = new signalR.HubConnectionBuilder()
    // .withUrl(url, {
    //   skipNegotiation: true,
    //   transport: signalR.HttpTransportType.WebSockets
    // })
    .withUrl(url)//尝试不跳过协商,对服务器上竟然成功。但是服务器在本地会无法连接，需要上面屏蔽的代码
    .configureLogging(signalR.LogLevel.Information)
    .build()

    signal.start().then(() => {
      debugger;
      if (window.Notification) {
        if (Notification.permission === 'granted') {
          console.log('允许通知')
        } else if (Notification.permission !== 'denied') {
          console.log('需要通知权限')
          Notification.requestPermission((permission) => { console.log("权限通知",permission) })
        } else if (Notification.permission === 'denied') {
          console.log('拒绝通知')
        }
      } else {
        console.error('浏览器不支持Notification')
      }
      console.log('连接成功');

      signal.on('Show', (res) => {
        debugger;
        console.log(res, '收到消息Show2')
      });  
      signal.on('ReceiveMessage', (res) => {
        debugger;
        console.log(res, '收到监听消息')
      });        
    })

    signal.onclose((err)=>{
        console.log("连接已经断开 执行函数onclose",err)
    })


   
  },
  methods: {
    initChatInfo(){      
      var me = this;
      // this.userGuid = localStorage.getItem("userGuid");
      this.open_kfid  = "wkH7yTDgAAFDT_4u7-UDFqujS1-GS1Nw";
      var params = {
        withCredentials: true,
        open_kfid:this.open_kfid
      };
      axios
       .post('/api/MyWx/GetKfWxChats',params)
       .then(
        (response) => {
          
          var replyData=response.result;          
debugger;
          this.chatinfos = replyData;
          this.userChatGuid = replyData[0].userChatGuid;

          me.initMessage();
        });      
    },
    initMessage(){      
      var params = {
        userGuid:this.userGuid,
        userChatGuid:this.userChatGuid        
      };

      axios
       .post('/api/Chat/GetUserChat',params)
       .then(
        (response) => {
          var replyData=response.data;          

          this.messages = replyData;
        });
      
    },
    addChat(){
      var params = {
        userGuid:this.userGuid
      };
      axios
       .post('/api/Chat/InsertUserChat',params)
       .then(
        (response) => {
          var newChat=response.data;          

          this.chatinfos.push(newChat);


        });      
    },
    selChatInfo(userChatGuidParam){
      this.userChatGuid = userChatGuidParam;
      this.initMessage();
    },
    clearMessage(){
      this.userGuid = localStorage.getItem("userGuid");
      var params = {
        userGuid:this.userGuid,
        userChatGuid:this.userChatGuid,
        messages:this.messages
      };

      axios
       .post('/api/Chat/ClearChat',params)
       .then(
        (response) => {          
          this.messages = [];
        });
      
    },    
    async sendMessage(message) {
      var me = this;
      if(message.trim()==""){
        me.alterError("请输入发送内容！");
        return;
      }
      this.messages.push({
        from: 'user',
        data: message,
      });
      var params = {
        userChatGuid:this.userChatGuid,
        userGuid:this.userGuid,
        messages:this.messages
      };
      this.askBtnDisabled = false;
      // var div = this.$(".messageBox mt-8");

      // var div = document.getElementById("mesarea");
      // if (div){
      //   div.scrollTop = div.scrollHeight - div.clientHeight;              
      // }

      
      setTimeout(function() {
                let chatDiv = document.getElementById("mesarea");
                chatDiv.scrollTop = chatDiv.scrollHeight;
              }, 100); 
      await axios
       .post('/api/Chat/Chat',params)
       .then((response) => {
            var replyData="";
            
            try{
              var reply = response.data.data.substring(response.data.data.lastIndexOf("bot:"));
              replyData = reply.split(':')[1];
              if(replyData==undefined){
                replyData = response.data.data;  
              }

              //清空发送的聊天
              me.currentMessage = '';
              this.askBtnDisabled = false;
            }
            catch(ex){
              replyData = response.data.data;
            }
            
            if(this.messages.length==1){
              this.initChatInfo();
            }            

            this.messages.push({
              from: 'bot',
              data: replyData, // Access the 'data' property of the response object
            });   
            

            setTimeout(function() {
                let chatDiv = document.getElementById("mesarea");
                chatDiv.scrollTop = chatDiv.scrollHeight;
              }, 100);            
        });
    },
    
    alterError(mes) {
         this.$notify({
           title: '失败',
           message: mes,
           type: 'error'
         });
     },
  },
};
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap');

.chatbox-container {
  /* position: fixed; */
  bottom: 24px;
  right: 24px;
  z-index: 1000;
  width: 100%;
  height: 90%;
}

.container {
  /* width: 360px; */
  height: 800px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  font-family: 'Roboto', sans-serif;
}

h1 {
  font-size: 24px;
  font-weight: 500;
  text-align: center;
  color: #222;
  padding: 16px;
  margin: 0;
  background-color: #f7f7f7;
  border-bottom: 1px solid #e7e7e7;
}

.messageBox {
  padding: 16px;
  flex-grow: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.messageFromUser,
.messageFromChatGpt {
  display: flex; }



.messageBox {
  max-height: 800px;
  overflow-y: auto;
  padding: 0 16px;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  flex-grow: 1;
}

.messageFromUser,
.messageFromChatGpt {
  display: flex;
  margin-bottom: 8px;
}

.userMessageWrapper,
.chatGptMessageWrapper {
  display: flex;
  flex-direction: column;
}

.userMessageWrapper {
  align-self: flex-end;
}

.chatGptMessageWrapper {
  align-self: flex-start;
}

.userMessageContent,
.chatGptMessageContent {
  max-width: 80%;
  padding: 8px 12px;
  border-radius: 18px;
  margin-bottom: 2px;
  font-size: 14px;
  line-height: 1.4;
}

.userMessageContent {
  background-color: #1877F2;
  color: white;
  border-top-left-radius: 0;
}

.chatGptMessageContent {
  background-color: #EDEDED;
  color: #222;
  border-top-right-radius: 0;
}

.userMessageTimestamp,
.chatGptMessageTimestamp {
  font-size: 10px;
  color: #999;
  margin-top: 2px;
}

.userMessageTimestamp {
  align-self: flex-end;
}

.chatGptMessageTimestamp {
  align-self: flex-start;
}

.inputContainer {
  display: flex;
  align-items: center;
  padding: 8px;
  background-color: #f0f0f0;
}

.messageInput {
  flex-grow: 1;
  border: none;
  outline: none;
  padding: 12px;
  font-size: 16px;
  background-color: white;
  border-radius: 24px;
  margin-right: 8px;
}

.clearButton {
  background-color: #1877F2;
  color: white;
  font-size: 16px;
  padding: 8px 16px;
  border: none;
  outline: none;
  cursor: pointer;
  border-radius: 24px;
  transition: background-color 0.3s ease-in-out;
}

.askButton {
  background-color: #1877F2;
  color: white;
  font-size: 16px;
  padding: 8px 16px;
  border: none;
  outline: none;
  cursor: pointer;
  border-radius: 24px;
  transition: background-color 0.3s ease-in-out;
}

.askButton:hover {
  background-color: #145CB3;
}

@media (max-width: 480px) {
  .container {
    width: 100%;
    max-width: none;
    border-radius: 0;
  }
}



.messageBox {
  padding: 16px;
  flex-grow: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.messageFromUser,
.messageFromChatGpt {
  display: flex;
}


.chatTitleDiv{
  margin: 10px 20px;
  position: relative;
  height: 100%;
  color: var(--color-neutral-8);
  padding: 10px 15px;
  border-radius: 2px;
  cursor: pointer;
  justify-content: space-between;
  background-color: black;
}

.chatTitleCurDiv{
  margin: 10px 20px;
  position: relative;
  height: 100%;
  color: var(--color-neutral-8);
  padding: 10px 15px;
  border-radius: 2px;
  cursor: pointer;
  justify-content: space-between;
  background-color: black;
  background-color: #1877F2;
}


.addChat {
  background-color: #1877F2;
  color: white;
  font-size: 14px;
  padding: 8px 16px;
  border: none;
  outline: none;
  cursor: pointer;  
  transition: background-color 0.3s ease-in-out;
}

</style>
